import web, datetime
import json, time

from Block import Block

db = web.database(dbn='sqlite', db='/etc/debrew/debrew')

# Profiles
def get_profiles():
    return db.select('profiles', order='id DESC')

def get_profile(id):
    try:
        return db.select('profiles', where='id=$id', vars=locals())[0]
    except IndexError:
        return None

def new_profile(title, text):
    return db.insert('profiles', title=title, content=text, posted_on=datetime.datetime.utcnow())

def del_profile(id):
    db.delete('profiles', where="id=$id", vars=locals())

def update_profile(id, title, text):
    db.update('profiles', where="id=$id", vars=locals(),title=title, content=text)


# Sections
def get_sections_by_profile_id(profile_id):
    return db.select('sections', where="profile_id = $profile_id", vars=locals())

def new_section(title, description, profile_id):
    db.insert('sections', title=title, description=description, profile_id=profile_id)

def del_section(id):
    db.delete('sections', where="id=$id", vars=locals())

def update_section(id, title, description, profile_id):
    db.update('sections', where="id=$id", vars=locals(), title=title, description=description, profile_id=profile_id)


# Blocks
def get_blocks_by_section_id(section_id):
    return db.select('blocks', order='idx', where='section_id = $section_id', vars=locals())

def update_block(id, settings, section_id, index):
    db.update('blocks', where="id=$id", vars=locals(), settings = settings, section_id=section_id, idx=index)

def del_block(id):
    db.delete('blocks', where="id=$id", vars=locals())

def new_block(type):
    return db.insert('blocks', name=type)

# Settings
def get_settings_by_block(block):
    return json.loads(block.settings)



# compile profile
def compile_profile(id):
    gcodes = "; Debrew Gcodes generated "+time.strftime("%c")+"\n\n"
    for section in get_sections_by_profile_id(id):
        gcodes += ";----------\n; Section: "+section.title+"\n;----------\n"
        gcodes += "M117 "+section.title+"; Send message\n"
        for block in Block.get_all_by_section_id(section.id):
            #gcodes += ";Block index: "+str(block.idx)+"\n"
            gcodes += block.get_gcodes()

    return gcodes
